package frmMantenimiento;

import cls.conexion;
import com.sun.glass.events.KeyEvent;
import frm.frmPrincipal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class frmFamilias extends javax.swing.JFrame {

    static conexion CP; // conexion con base de datos

    public frmFamilias() throws ClassNotFoundException, SQLException {
        initComponents();
        setLocationRelativeTo(null);
        btnFinalizarModifica.setVisible(false);
        btnfinalizar.setVisible(false);
        botonesquitar();
        CP = new conexion("proyecto2", "usrUTN", "12345");
        verdatos();
    }

    private void limpiarRd() {
        rdNo.setSelected(false);
        rdSi.setSelected(false);
        rdNo.setEnabled(true);
        rdSi.setEnabled(true);
    }

    // quitar los botones
    public void botonesquitar() {
        txtDesc.setVisible(false);
        txtcodigo.setVisible(false);
        rdNo.setVisible(false);
        rdSi.setVisible(false);

        jLabel1.setVisible(false);
        jLabel2.setVisible(false);
        jLabel4.setVisible(false);
    }

    //  muestras los botoones
    public void botonesver() {
        txtDesc.setVisible(true);
        txtcodigo.setVisible(true);
        rdNo.setVisible(true);
        rdSi.setVisible(true);
        jLabel1.setVisible(true);
        jLabel2.setVisible(true);
        jLabel4.setVisible(true);
    }

    // muestras los datos de la base de datos a la tabla
    public void verdatos() {
        DefaultTableModel modelo = (DefaultTableModel) tblFamilia.getModel();
        Object[] fila = new Object[6];
        modelo.setRowCount(0);
        try {
            ResultSet datos = this.CP.select("*", "\"schUTN\".familia_articulo", "");
            while (datos.next()) {
                fila[0] = datos.getString(1);
                fila[1] = datos.getString(2);
                fila[2] = datos.getString(3);
                modelo.addRow(fila);
            }
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblFamilia = new javax.swing.JTable();
        btnInsertar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnAtras = new javax.swing.JButton();
        txtcodigo = new javax.swing.JTextField();
        txtDesc = new javax.swing.JTextField();
        btnfinalizar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnFinalizarModifica = new javax.swing.JButton();
        rdNo = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        rdSi = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("FAMILIAS");
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        tblFamilia.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "cod_familia", "descripcion", "activo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblFamilia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblFamiliaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblFamilia);
        if (tblFamilia.getColumnModel().getColumnCount() > 0) {
            tblFamilia.getColumnModel().getColumn(0).setResizable(false);
            tblFamilia.getColumnModel().getColumn(1).setResizable(false);
            tblFamilia.getColumnModel().getColumn(2).setResizable(false);
        }

        btnInsertar.setText("Insertar");
        btnInsertar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertarActionPerformed(evt);
            }
        });

        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnAtras.setText("Atras");
        btnAtras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAtrasActionPerformed(evt);
            }
        });

        txtDesc.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDescFocusLost(evt);
            }
        });

        btnfinalizar.setText("Finalizar");
        btnfinalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnfinalizarActionPerformed(evt);
            }
        });

        jLabel1.setText("Codigo Familia");

        jLabel2.setText("Descripcion");

        btnFinalizarModifica.setText("Finalizar");
        btnFinalizarModifica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinalizarModificaActionPerformed(evt);
            }
        });

        rdNo.setText("No");
        rdNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdNoActionPerformed(evt);
            }
        });
        rdNo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rdNoFocusLost(evt);
            }
        });

        jLabel4.setText("Activo");

        rdSi.setText("SI");
        rdSi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdSiActionPerformed(evt);
            }
        });
        rdSi.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rdSiFocusLost(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4)
                                .addGap(36, 36, 36)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnfinalizar, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(btnFinalizarModifica, javax.swing.GroupLayout.Alignment.TRAILING)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(42, 42, 42)
                                .addComponent(rdSi)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(rdNo)
                                .addGap(88, 88, 88)))))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btnModificar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnInsertar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(btnInsertar)
                        .addGap(26, 26, 26)
                        .addComponent(btnModificar)
                        .addGap(34, 34, 34)
                        .addComponent(btnEliminar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(btnFinalizarModifica)
                        .addComponent(btnfinalizar)
                        .addComponent(jLabel2))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnAtras)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(rdNo)
                        .addComponent(rdSi)))
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // boton insertar
    private void btnInsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertarActionPerformed
        limpiar();
        btnfinalizar.setVisible(true);
        btnFinalizarModifica.setVisible(false);
        botonesver();
        this.txtcodigo.requestFocus();
    }//GEN-LAST:event_btnInsertarActionPerformed

    // boton atras regresa a la ventana principal
    private void btnAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtrasActionPerformed
        setVisible(false);
        frmPrincipal atras = new frmPrincipal();
        atras.setVisible(true);
    }//GEN-LAST:event_btnAtrasActionPerformed

    // boton modificar
    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        limpiar();
        btnFinalizarModifica.setVisible(true);
        btnfinalizar.setVisible(false);
        botonesver();
        this.txtcodigo.requestFocus();
    }//GEN-LAST:event_btnModificarActionPerformed

    //evento para seleccionar los datos de la tabla a los txt field
    private void tblFamiliaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblFamiliaMouseClicked

        limpiarRd();
        String cod;
        DefaultTableModel modelo = (DefaultTableModel) tblFamilia.getModel();
        int vector[] = tblFamilia.getSelectedRows();
        int in = tblFamilia.getSelectedRow();

        cod = (String) tblFamilia.getValueAt(in, 0);
        txtcodigo.setText(cod);

        cod = (String) tblFamilia.getValueAt(in, 1);
        txtDesc.setText(cod);

        cod = (String) tblFamilia.getValueAt(in, 2);
        if (cod.equals("S")) {
            rdSi.setSelected(true);

        } else {
            rdNo.setSelected(true);
        }

        if (rdSi.isSelected()) {
            rdNo.setEnabled(false);
        } else {
            rdNo.setEnabled(true);
        }

        if (rdNo.isSelected()) {
            rdSi.setEnabled(false);

        } else {
            rdSi.setEnabled(true);
        }

    }//GEN-LAST:event_tblFamiliaMouseClicked

    // finaliza el insert a la base de datos
    private void btnfinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnfinalizarActionPerformed
        try {
            if (!(this.txtcodigo.getText().charAt(0) == ' ')) {
                try {
                    String si = "";
                    if (rdSi.isSelected()) {
                        si = "S";
                    } else {
                        if (rdNo.isSelected()) {
                            si = "N";
                        }
                    }
                    boolean resultado = this.CP.insert("\"schUTN\".familia_articulo",
                            "(" + "'" + this.txtcodigo.getText() + "'"
                            + ", " + "'" + this.txtDesc.getText() + "' , " + "'"
                            + si + "' " + ");");
                } catch (Exception e) {
                    System.out.printf("Error: " + e.toString());
                }
                limpiar();
                int validar = JOptionPane.showConfirmDialog(
                        null,
                        "Deseas Realizar Otra operacion",
                        "  ",
                        JOptionPane.YES_NO_OPTION);
                if (validar == JOptionPane.YES_OPTION) {
                    verdatos();
                } else {
                    verdatos();
                    jLabel1.setVisible(false);
                    jLabel2.setVisible(false);
                    jLabel2.setVisible(false);
                    jLabel4.setVisible(false);
                    txtDesc.setVisible(false);
                    txtcodigo.setVisible(false);
                    rdNo.setVisible(false);
                    rdSi.setVisible(false);
                    btnfinalizar.setVisible(false);
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Codigo Obligatorio");
        }

        limpiarRd();
    }

    // metodo que reestablese los valores
    private void limpiar() {
        txtcodigo.setText("");
        txtDesc.setText("");

    }//GEN-LAST:event_btnfinalizarActionPerformed

    // metodo para teminar la modificacion
    private void btnFinalizarModificaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarModificaActionPerformed
        String cod;
        DefaultTableModel modelo = (DefaultTableModel) tblFamilia.getModel();
        int vector[] = tblFamilia.getSelectedRows();
        int in = tblFamilia.getSelectedRow();
        if (in == -1) {
            JOptionPane.showMessageDialog(null, "Selecione un valor valido");
        } else {
            for (int i = 0; i < vector.length; i++) {
                cod = (String) tblFamilia.getValueAt(in, 0);
                try {
                    String si = "";
                    if (rdSi.isSelected()) {
                        si = "S";
                    } else {
                        if (rdNo.isSelected()) {
                            si = "N";
                        }
                    }
                    boolean resultado = this.CP.actualizar("\"schUTN\".familia_articulo",
                            " cod_familia= " + "'" + this.txtcodigo.getText() + "'"
                            + ", " + " descripcion= " + " '" + this.txtDesc.getText() + "' , "
                            + " activo= " + "'" + si + "' ", "cod_familia= " + "'" + cod + "'");
                } catch (Exception e) {
                    System.out.printf("Error: " + e.toString());
                }
            }
        }
        verdatos();
        botonesquitar();
        limpiarRd();
        btnFinalizarModifica.setVisible(false);
        limpiar();
    }//GEN-LAST:event_btnFinalizarModificaActionPerformed

    // metodo para eliminar
    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        int validar = JOptionPane.showConfirmDialog(
                null,
                "Estas Seguro?",
                " CUIDADO",
                JOptionPane.YES_NO_OPTION);
        if (validar == JOptionPane.YES_OPTION) {
            try {
                boolean resultado = this.CP.eliminar("\"schUTN\".familia_articulo",
                        "cod_familia= " + "'" + this.txtcodigo.getText() + "'");
            } catch (Exception e) {
                System.out.printf("Error: " + e.toString());
            }
            verdatos();
        } else {
            verdatos();
        }
        botonesquitar();
        btnFinalizarModifica.setVisible(false);
        btnfinalizar.setVisible(false);
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void rdSiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdSiActionPerformed
        if (rdSi.isSelected()) {
            rdNo.setEnabled(false);
            
           if(this.btnFinalizarModifica.isEnabled()==true)
           {
               this.btnFinalizarModifica.requestFocus();
           }
          
           
               if (this.btnfinalizar.isEnabled()==true) {
                   
                   this.btnfinalizar.requestFocus();
               }
               
           
            
        } else {
            rdNo.setEnabled(true);
        }
    }//GEN-LAST:event_rdSiActionPerformed

    private void rdNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdNoActionPerformed
        if (rdNo.isSelected()) {
            rdSi.setEnabled(false);
             if(this.btnFinalizarModifica.isEnabled()==true)
           {
               this.btnFinalizarModifica.requestFocus();
           }
          
           
               if (this.btnfinalizar.isEnabled()==true) {
                   
                   this.btnfinalizar.requestFocus();
               }
               

        } else {
            rdSi.setEnabled(true);
        }
    }//GEN-LAST:event_rdNoActionPerformed

    private void rdNoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rdNoFocusLost
         if (rdNo.isSelected()==true) {
            rdSi.setEnabled(false);
                  if(this.btnFinalizarModifica.isEnabled()==true)
           {
               this.btnFinalizarModifica.requestFocus();
           }
          
           
               if (this.btnfinalizar.isEnabled()==true) {
                   
                   this.btnfinalizar.requestFocus();
               }
               
        } else {
            rdSi.setEnabled(true);
        }
       
       if(rdNo.isSelected()==false&&rdSi.isSelected()==false)
       {
           this.rdSi.requestFocus();
       }
    }//GEN-LAST:event_rdNoFocusLost

    private void rdSiFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rdSiFocusLost
         if (rdSi.isSelected()==true) {
            rdNo.setEnabled(false);
                  if(this.btnFinalizarModifica.isEnabled()==true)
           {
               this.btnFinalizarModifica.requestFocus();
           }
          
           
               if (this.btnfinalizar.isEnabled()==true) {
                   
                   this.btnfinalizar.requestFocus();
               }
               
        } else {
            rdNo.setEnabled(true);
        }
    }//GEN-LAST:event_rdSiFocusLost

    private void txtDescFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDescFocusLost
        if (rdSi.isSelected()==false && rdNo.isSelected()==false) {
            this.rdSi.requestFocus();
        }else{
            if (rdSi.isSelected()==true) {
                rdSi.requestFocus();
            }else{
                rdNo.requestFocus();
            }
        }
    }//GEN-LAST:event_txtDescFocusLost

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
          char tecla=evt.getKeyChar();
        if(tecla==KeyEvent.VK_ESCAPE)
        {
            setVisible(false);
            frmPrincipal F = new frmPrincipal();
            F.setVisible(true);
          
            
        }
    }//GEN-LAST:event_formKeyPressed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(() -> {
            try {
                new frmFamilias().setVisible(true);
            } catch (ClassNotFoundException | SQLException ex) {
                Logger.getLogger(frmFamilias.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAtras;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnFinalizarModifica;
    private javax.swing.JButton btnInsertar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnfinalizar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rdNo;
    private javax.swing.JRadioButton rdSi;
    private javax.swing.JTable tblFamilia;
    private javax.swing.JTextField txtDesc;
    private javax.swing.JTextField txtcodigo;
    // End of variables declaration//GEN-END:variables
}
